<template>
    <UxDialog :visible.sync="visible" @scroll="onScroll($event)" @show="onShow()" @close="onClose()">

        <div class="product-select" :type="type">
            <h2>Products</h2>

            <div class="select-tab">
                <a v-for="item in tables" :key="item.shop_id" @click="setTab(item.shop_id)" :class="{ active: tab == item.shop_id }">
                    <span v-if="item.shop_id == 0">
                        <img src="@/assets/images/store/store-tabs-self.png" alt="">
                        <em>Product templates</em>
                    </span>
                    <StoreIconName v-else :item="item.store"></StoreIconName>
                </a>
            </div>
            <div class="select-search">
                <UserSearchName shape="solid" v-model="form.name" placeholder="Template" @change="doSearch($event)" />
            </div>

            <div class="scroll-init" v-if="!table_active.inited">
                <UxLoading2 />
            </div>

            <UxSearchEmpty v-else-if="table_visible.length == 0" />

            <template v-else>

                <div class="table-title" :class="{border: scroll_top>0}">
                    <span>Template</span>
                    <span>Product information</span>
                    <span>Designs</span>
                    <span>Price</span>
                </div>

                <div class="table-scroller" ref="scroller" @scroll="onScroll()">

                    <ul class="table-body">

                        <li v-for="item in table_visible" :key="item.id" :class="{'table-brand': item.tag_design_info || item.pack_design_info}" @click="selecdtItem(item)">
                            <div class="table-model">
                                <CommonStoreTemplatePreview v-if="item.source == 'shop'" :item="item" />
                                <CommonTemplatePreview v-else :pieces="item.design_list" :models="item.model_img" :baseColor="getColorPreview(item)" />
                                <h3 v-text="item.title"></h3>
                            </div>

                            <div class="table-info" :suit="item.data.length > 1">
                                <div class="table-info-pro" v-for="product in item.data" :key="item.id + '-' + product.design_id">
                                    <div class="table-info-select">
                                        <div class="table-info-title" v-text="product.sub_title"></div>
                                        <div class="table-info-color">
                                            <em v-for="color in product.color_list" :key="color.color_id" :style="{backgroundColor: color.color_num}"></em>
                                        </div>

                                        <div class="table-info-size">
                                            <em v-if="product.size_list.length  == 0"> -- </em>
                                            <em v-else-if="product.size_list.length  == 1" v-text="product.size_list[0].size_name"></em>
                                            <em v-else v-text="product.size_list[0].size_name + '-' +product.size_list[product.size_list.length-1].size_name"></em>
                                        </div>
                                    </div>

                                    <div class="table-info-design">
                                        <p v-if="!product.design_info || product.design_info.length == 0">- -</p>
                                        <CommonSurfacePreview v-else :design="product.design_info" />
                                    </div>

                                    <div class="table-info-cost">
                                        <CommonLevelDiscount v-if="product.low_price == product.high_price" :level="levelInfo || item" :price="product.low_price + product.extra_price" :blank="product.is_blank" type="unit|discount|icon" />
                                        <CommonLevelDiscount v-else :level="levelInfo || item" :price="(product.low_price + product.extra_price) +'-'+ (product.high_price + + product.extra_price)" :blank="product.is_blank" type="unit|discount|icon" />
                                    </div>
                                </div>
                            </div>

                            <CommonBrandPreview :tag="item.tag_design_info" :pack="item.pack_design_info" :currencyCover="levelInfo" />
                        </li>

                    </ul>

                    <div class="scroll-status" v-if="table_visible.length >= 0">
                        <span v-show="loadmore == 'loading'">loading</span>
                        <span v-show="loadmore == 'nomore'"> </span>
                        <span v-show="loadmore == 'waiting'">scroll to bottom load more</span>
                    </div>
                </div>

            </template>
        </div>

    </UxDialog>

</template>
<script>
export default {
    name: "SelectDesign",
    props: ["value", "disabled", 'type', 'levelInfo'],
    data () {
        return {
            tab: 0,
            scroll_top: 0,
            tables: [
                {
                    shop_id: 0,
                    form: { name: '', page_num: 1, page_size: 10 },
                    inited: false,
                    table: [],
                    total: 0,
                    loadmore: 'waiting', // [loading|nomore|waiting];
                }
            ],
            // storeList: [],
            set_tab_ing: false,
        };
    },
    computed: {
        visible: {
            get () {
                return !!this.value;
            },
            set (v) {
                this.$emit("input", v);
            },
        },

        table_active () {
            const tab = this.tab || 0;
            return this.tables.filter(item => item.shop_id == tab)[0] || {}
        },
        table_visible () {

            const active = this.table_active;
            const disabled = this.disabled || []
            const map = new Map();
            const type = active.shop_id ? 'store' : 'temp';
            const table = active.table || []

            disabled.map(item => map.set(item.type + item.id, true));

            return table.filter(item => !map.get(type + item.id))
        },
        loadmore: {
            get () {
                return this.table_active.loadmore
            },
            set (val) {
                this.table_active.loadmore = val;
            }
        },
        form: {
            get () {
                return this.table_active.form
            },
            set (val) {
                this.table_active.form = val;
            }
        },
    },
    methods: {

        // 对话框显示时
        onShow () {
            // if (this.table_visible.length == 0) {
            //     this.getData();
            // }
            this.type != 'store' && this.tables.length == 1 && this.getStore();

            // 每次打开都重新获取值
            this.tables.map(item => {
                item.form.name = ''
                item.form.page_num = 1;
                item.inited = false;
                item.table = []
                item.total = 0;
                item.loadmore = "waiting";
            })
            this.getData();
        },

        // 关闭
        onClose () {
            this.$emit("input", false);
        },

        //获得全部店铺
        async getStore () {
            let response = await this.$http("UserStore.getAllLinkStore");
            if (response.code == 0) {

                const stores = response.data || [];
                stores.map(item => {
                    this.tables.push({
                        shop_id: item.id,
                        form: { page_num: 1, page_size: 10 },
                        table: [],
                        total: 0,
                        store: item,
                        inited: false,
                        loadmore: null, // [loading|nomore|waiting];
                    })
                })


                // this.$uxMessage.success(response.msg || "success");
            } else {
                // this.$uxMessage.error(response.msg || "error");
                // 提示
            }
        },


        // 模板列表
        async getTemplateList (request) {

            const result = {
                total: 0,
                list: []
            }
            const response = await this.$http("storeTemplate.getList", request)

            result.list = response.data || []
            result.total = response.total || []

            result.list = result.list.map(item => {
                return {
                    id: item.id,
                    source: 'template',
                    tag_design_info: item.tag_design_info,
                    pack_design_info: item.pack_design_info,
                    img_url: item.tem_img_url,
                    title: item.template_name,
                    color_base: item.color_base || item.show_color_num || '',
                    color_list: item.color_list || [],
                    model_img: item.model_img || [],
                    user_level: item.user_level,
                    design_list: item.design_list || [],
                    user_discount: item.user_discount,
                    data: [{
                        spu: item.spu,
                        title: item.title,
                        model_img: item.model_img,
                        design_id: item.id,
                        color_base: item.color_base,
                        size_list: item.size_list || [],
                        color_list: item.color_list || [],
                        design_info: item.design_list || [],
                        low_price: item.low_price || 0,
                        high_price: item.high_price || 0,
                        extra_price: item.extra_price,
                        is_blank: !!item.is_blank,
                    }],
                }
            })

            return result;

        },

        // 商店商品列表
        async getStoreProductList (request) {

            const result = {
                total: 0,
                list: []
            }

            const shop_id = this.table_active.shop_id;
            const response = await this.$http("UserStore.getShopProductListSuit/" + shop_id, request);
            const data = response.data || {};

            result.list = data.product_info || []
            result.total = data.total || []

            result.list.map(product => {
                const custom = (product.data || []).filter(p => (p.design_info || []).filter(i => i.custom_count > 0).length);
                product.custom = custom.length > 0;
                product.source = 'shop'
            })


            return result;
        },

        // 获取列表数据
        async getData () {

            const active = this.table_active;
            const shop_id = active.shop_id;
            const request = {
                page_num: active.form.page_num,
                page_size: active.form.page_size,
                name: active.form.name,
                status: 0,
            };

            try {
                active.loadmore = 'loading'
                const result = shop_id ? await this.getStoreProductList(request) : await this.getTemplateList(request);

                active.inited = true;
                active.table.push(...result.list);
                active.total = result.total;
                active.loadmore = active.table.length >= result.total ? "nomore" : "waiting";
            } catch (error) {
                active.inited = true;
                active.loadmore = 'error';
                console.log(error)
            }
        },

        // 搜索
        doSearch () {
            const active = this.table_active;

            if (active.loadmore == 'loading') {
                // 加载中
            } else {
                active.form.page_num = 1;
                active.inited = false;
                active.table = []
                active.total = 0;
                active.loadmore = "waiting";

                this.getData().then(() => this.$refs.scroller && this.$refs.scroller.scrollTo(0, 0))
            }
        },

        // 颜色预览
        getColorPreview (item) {
            const color = item.color_base;
            const list = item.color_list || [];
            const select = list.filter((i) => i.color_num == color || i.color_id == color);
            return select[0] || list[0];
        },

        // 清空数据
        setTab (id) {
            this.tab = id;
            const active = this.tables.filter(item => item.shop_id == id)[0] || {}
            const scroller = this.$refs.scroller
            scroller && scroller.scrollTo(0, 0)
            !active.inited && this.getData()
        },

        // 滚动事件
        onScroll (event) {

            const scroller = this.$refs.scroller
            if (!scroller) {
                // 没有滚动
            } else if (this.loadmore == "waiting") {
                const top = scroller.scrollTop || 0;
                const offset = 10;
                const inner = scroller.scrollHeight || 0
                const outer = scroller.clientHeight || 0

                this.scroll_top = top;
                if (inner - outer - top < offset) {
                    this.loadmore = "loading";
                    this.form.page_num += 1;
                    this.getData();
                }
            }

        },


        // 选中
        selecdtItem (product) {

            const sellect = (product.data || []).map(item => {
                return {
                    spu: item.spu, //商品的SPU用于确认SKU
                    title: item.title, //标题
                    model_img: item.model_img || [],
                    design_list: item.design_info, //设计信息
                    design_id: item.design_id, //商品来源
                    extra_price: item.extra_price, // 设计面价格
                    is_blank: item.is_blank, // 空白模板
                    color_base: item.color_base,

                    source: product.source, //商品来源
                    tag_design_info: product.tag_design_info, // 吊牌
                    pack_design_info: product.pack_design_info // 包装
                };
            })

            this.$emit("selectDesign", sellect);
            this.onClose();
        },
    },
    created () { },
    mounted () { },
};
</script>
<style lang="scss" scoped>
.product-select {
    box-sizing: border-box;
    width: calc(100vw - 80px);
    height: calc(100vh - 80px);
    max-width: 1096px;
    max-height: 800px;
    border-radius: 10px;
    display: flex;
    flex-direction: column;
    position: relative;
    overflow: hidden;

    & > h2 {
        font-size: 26px;
        font-family: Roboto-Medium, Roboto;
        font-weight: 500;
        color: #000000;
        line-height: 32px;
        padding: 24px 24px;
    }

    .search-empty {
        margin: 12px 32px 32px;
        flex: 1;
        border: none;
    }

    .scroll-status {
        text-align: center;
        line-height: 50px;
        text-align: center;
        font-size: 14px;

        color: #666666;
    }

    &[type='store'] {
        .select-tab {
            display: none;
        }

        .select-search {
            position: absolute;
            top: 32px;
            right: 32px;
            width: 252px;
            height: 32px;
            padding: 0;
        }
    }
}

.scroll-init {
    flex: 1;
    position: relative;
    display: flex;
}

.select-tab {
    display: flex;
    box-sizing: border-box;
    margin-top: -8px;
    padding: 0 20px;
    flex-wrap: wrap;
    a {
        width: 252px;
        height: 40px;
        box-sizing: border-box;
        padding: 0 14px 0 12px;
        background: #ffffff;
        border-radius: 8px;
        border: 1px solid #e6e6e6;
        cursor: pointer;
        display: flex;
        align-items: center;
        position: relative;
        overflow: hidden;
        margin: 4px;

        & > span {
            display: flex;
            align-items: center;
            em {
                font-size: 14px;
                font-family: Roboto-Regular, Roboto;
                font-weight: 400;
                color: #000000;
                line-height: 16px;
            }

            img {
                width: 20px;
                height: 20px;
                line-height: 18px;
                margin-right: 4px;
                text-align: center;
                font-size: 20px;
                color: #ea4c89;
            }
        }

        &::before {
            content: '';
            position: absolute;
            left: 0;
            bottom: 0;
            right: 0px;
            height: 2px;
            background: transparent;
            transition: all 0.2s;
        }

        &:hover {
            &::before {
                background-color: #f6b2cd;
            }
        }

        &.active {
            &::before {
                background-color: #ea4c89;
            }

            &.error::before {
                background-color: #db080d;
            }
        }
    }
}

.select-search {
    position: relative;
    padding: 16px 24px 20px;
    width: 252px;
    .user-search-name {
        height: 36px;
    }
}
.table-title {
    display: flex;
    align-items: center;
    border-radius: 8px;
    border: 1px solid #e6e6e6;
    height: 40px;
    min-height: 40px;
    margin: 0 24px;
    position: relative;

    span {
        width: 25%;
        text-align: center;
        font-size: 14px;
        font-family: Roboto-Medium, Roboto;
        font-weight: 500;
        color: #292929;
        line-height: 20px;
    }

    &::after {
        content: '';
        position: absolute;
        left: 0;
        right: 0;
        top: 100%;
        margin-top: 12px;
        height: 1px;
        background-color: #e6e6e6;
        opacity: 0;
    }

    &.border::after {
        opacity: 1;
    }
}

.table-scroller {
    flex: 1;
    overflow: auto;
    margin-top: 12px;
}

.table-body {
    margin: 0 24px;

    & > li {
        display: flex;
        align-items: center;
        position: relative;
        cursor: pointer;
        border-radius: 8px;
        border: 1px solid #e6e6e6;
        margin-bottom: 12px;

        &:hover {
            box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.12);
        }
    }

    .table-model {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 12px;
        width: 25%;
        position: relative;
        box-sizing: border-box;

        .template-preview,
        .store-preview {
            width: 160px;
            margin: 0 auto;
            position: initial;

            &::v-deep .process-icon {
                left: 10px;
                top: 10px;
            }
        }

        h3 {
            font-size: 14px;
            color: #666666;
            line-height: 16px;
            margin: 8px auto 0;
            font-weight: normal;
            max-width: 160px;
            text-align: center;
            overflow: hidden;
            text-overflow: ellipsis;
        }
    }

    .table-info {
        flex-direction: column;
        align-items: center;
        width: 75%;

        h3 {
            padding: 10px 0;
            font-size: 14px;

            color: #000000;
            font-weight: 500;
            line-height: 16px;
        }
        p {
            margin: 8px 0;
            line-height: 20px;
            font-size: 14px;

            color: #666666;
        }

        .table-info-pro {
            width: 100%;
            display: flex;
            align-items: center;
            font-size: 14px;
            font-family: Roboto-Regular, Roboto;
            font-weight: 400;
            color: #000000;
            line-height: 16px;
            word-break: break-word;
            position: relative;

            & + .table-info-pro::before {
                content: '';
                position: absolute;
                left: 24px;
                top: 0;
                right: 24px;
                height: 1px;
                background-color: #ebebeb;
            }
        }

        .table-info-select {
            width: 33.33%;
            padding: 12px 24px;
            box-sizing: border-box;
        }

        .table-info-design {
            width: 33.33%;
            padding: 12px;
            box-sizing: border-box;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .table-info-cost {
            width: 33.33%;
            padding: 12px;
            box-sizing: border-box;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 14px;
            color: #000000;
            line-height: 16px;
            .level-discount {
                font-size: 14px;
                justify-content: center;
                &[currency='JPY'] {
                    flex-wrap: wrap;
                    &::v-deep span {
                        margin: 0;
                        &[name='discount'] {
                            width: 100%;
                            margin: 4px;
                            text-align: center;
                        }
                    }
                }
            }
        }

        .table-info-title {
            padding-bottom: 10px;
            display: none;
        }

        .table-info-color {
            position: relative;
            display: flex;
            flex-wrap: wrap;
            padding-left: 46px;
            padding-bottom: 10px;
            line-height: 16px;
            &::before {
                content: 'Color:';
                position: absolute;
                left: 0;
                top: 0;
            }
            & > em {
                margin: 2px;
                width: 12px;
                height: 12px;
                box-sizing: border-box;
                border-radius: 1px;
                border: 1px solid rgba(0, 0, 0, 0.16);
            }
        }

        .table-info-size {
            position: relative;
            display: flex;
            flex-wrap: wrap;
            padding-left: 48px;
            line-height: 16px;
            &::before {
                content: 'Size:';
                position: absolute;
                left: 0;
                top: 0;
            }
            & > em {
                line-height: 16px;
            }
        }

        // 套装
        &[suit] {
            .table-info-title {
                display: block;
            }

            .table-info-pro:first-child {
                padding-top: 20px;
            }
            .table-info-pro:last-child {
                padding-bottom: 20px;
            }
        }
    }

    .brand-preview {
        position: absolute;
        left: 0;
        bottom: 0;
        width: 100%;
        cursor: default;
        border-top: 1px solid #e6e6e6;
        display: none;
    }

    & > li.table-brand {
        padding-bottom: 40px;
        .brand-preview {
            display: flex;
        }
    }
}
</style>
